package com.oly.cms.web.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson2.JSONObject;
import com.grace.common.config.GraceConfig;
import com.grace.common.core.domain.AjaxResult;
import com.grace.common.utils.StringUtils;
import com.grace.common.utils.ip.IpUtils;

import java.util.Arrays;
import com.oly.cms.general.service.taglib.WebTag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** 指定某些管理IP才能访问拦截器 */
@Component
public class IPInterceptor implements HandlerInterceptor {

    @Autowired
    private WebTag webTag;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 过滤ip,若用户在白名单内，则放行
            String ipAddress = IpUtils.getIpAddr(request);
            String ips = webTag.selectCmsWebByWebName(GraceConfig.getOnlyCode()).getManageIp();
            if (StringUtils.isEmpty(ips)) {
                return true;
            } else if (Arrays.asList(StringUtils.split(ips)).contains(ipAddress)) {
                return true;
            } else {
                response.setHeader("Content-Type", "text/html; charset=UTF-8");
                response.getWriter().println(JSONObject.from(AjaxResult.error("该地址不允许访问!")));
                return false;
            }
    }
}
